//
//  UIButton+extension.swift
//  Weibo
//
//  Created by zyc on 16/6/3.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit

extension UIButton {
    
    //Initializer 'init()' with Objective-C selector 'init' conflicts with implicit initializer 'init()' with the same Objective-C selector: 自定义的init方法和NSObject的init方法冲突
    //在定义swift的函数时，如果函数的参数有可能在某个时间被设为nil，或者有可能被传一个nil，则将该参数设为可选。
    convenience init (title: String,
        titleColor: UIColor = UIColor.darkGrayColor(),
        font: CGFloat = 12,
        image: String? = nil,
        backGroundImage: String? = nil,
        target: AnyObject? = nil,
        action: String? = nil,
        event: UIControlEvents = .TouchUpInside) {
            
            self.init()
            
            self.setTitle(title, forState: .Normal)
            
            self.setTitleColor(titleColor, forState: .Normal)
            
            self.titleLabel?.font = UIFont.systemFontOfSize(font)
            
            if let image = image {
                
                self.setImage(UIImage(named: image), forState: .Normal)
                
                self.setImage(UIImage(named: "\(image)_highlighted"), forState: .Highlighted)
                
            }
            
            if let backGroundImage = backGroundImage {
                
                self.setBackgroundImage(UIImage(named: backGroundImage), forState: .Normal)
                
                self.setBackgroundImage(UIImage(named: "\(backGroundImage)_highlighted"), forState: .Highlighted)
                
            }
            
            //action如果直接写，可以直接用字符串，如果作为参数传递，必须使用 selector
            let selector = Selector(action!)
            
            self.addTarget(target, action: selector, forControlEvents: event)
            
    }

}